package net.ojbk.timeSpace.test.web.handllers.impl;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import net.ojbk.timeSpace.test.beans.APIResult;
import net.ojbk.timeSpace.test.beans.InfoAxisBlade;
import net.ojbk.timeSpace.test.beans.TimeAxis;
import net.ojbk.timeSpace.test.beans.User;
import net.ojbk.timeSpace.test.common.api.userApi.APIUserCode;
import net.ojbk.timeSpace.test.service.IAxisService;
import net.ojbk.timeSpace.test.web.handllers.IUserController;

@Controller
public class UserController implements IUserController {

	@Autowired
	@Qualifier("axisService")
	IAxisService axisService;

	@Override
	@RequestMapping("/index.do")
	public ModelAndView doIndex(HttpSession session) {
		ModelAndView mv = new ModelAndView();
		User user = (User) session.getAttribute("user");
		if (user != null) {
			mv.setViewName("forward:WEB-INF/jsp/home.jsp");

			List<TimeAxis> timeAxiss = axisService.getAllAxisByUid(user.getUid());
			TimeAxis timeAxis = timeAxiss.get(0);
			// 加入timaAxis
			mv.addObject("timeAxis", timeAxis);
			
			
			List<InfoAxisBlade> infoAxisBlades = axisService.getAllInfoAxisBlade(timeAxis.getAxisId());
			Collections.sort(infoAxisBlades, new Comparator<InfoAxisBlade>() {

				@Override
				public int compare(InfoAxisBlade o1, InfoAxisBlade o2) {
					
					return o2.getPushDate().compareTo(o1.getPushDate());
					
				}
				
			});
			
			
			mv.addObject("infoAxisBlades", infoAxisBlades);
			
			
			return mv;
		} else {
			mv.setViewName("redirect:noLoginHome.html");
			return mv;
		}
	}

	@Override
	@RequestMapping(value = "/isLogin.do")
	@ResponseBody
	public Object doIsLogin(HttpSession session) {
		// TODO Auto-generated method stub
		if (session.getAttribute("user") != null) {
			boolean isLogin = true;
			return APIResult.createSuccess(new APIUserCode(), isLogin);
		} else {
			return APIResult.createFail(new APIUserCode(), "未登录");
		}
	}

	@Override
	@RequestMapping("/logout.do")
	public String doLogout(HttpSession session) {
		// TODO Auto-generated method stub
		return "redirect:http://ojbk.net/center/logout.do";
	}

}
